package com.project.myPackage.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

public class ZxingUtil {

    public static BufferedImage createImage(String text) throws Exception {
        // 配置二维码参数
        Map<EncodeHintType, Object> map = new HashMap<>();
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 纠错级别
        map.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 字符编码
        map.put(EncodeHintType.MARGIN, 1); // 边距

        // 生成二维码矩阵
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        BitMatrix bitMatrix = multiFormatWriter.encode(text, BarcodeFormat.QR_CODE, 300, 300, map);

        // 创建 BufferedImage 对象
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 填充二维码像素
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }

        return image;
//        return imageToString(image);
    }

//    public static BufferedImage imageToString(BufferedImage image) throws IOException {
//        ByteArrayOutputStream os = new ByteArrayOutputStream();
//        ImageIO.write(image, "png", os);
//        return Base64.encodeBase64String(os.toByteArray());
//    }
}
